var Piece = pi.base.extend({
    "$Init":function(_id,_user,_color,_value,_element){
        this.environment.setHistory([]).
        environment.setMovement([]);
    
        this.environment.
        setId(_id).environment.
        setUser(_user).environment.
        setElement(_element).environment.
        setColor(_color).environment.
        setValue(_value).environment;

        this.setClassName();
        return this;
    },
    "setClassName":function(){
        this.environment.getElement().attribute.setClass("Piece Color_{0} Value_{1}".format(this.environment.getColor(),this.environment.getValue()));
    },
    "blur":function(){
        if(debug || (this.environment.getColor()==main.engine.environment.getTable().environment.getUser().environment.getColor()) ){
          var table = main.engine.environment.getTable();
          this.environment.getElement().attribute.removeClass("Selected");
          table.environment.setActivePiece(null);
          
          for(var i=0, len=table.element.getHighlight().length; i<len; i++){
            table.element.getHighlight()[i].remove();
          }
          
          table.element.setHighlight([]);
        }
    },
    "focus":function(){
        if( debug || (this.environment.getColor()==main.engine.environment.getTable().environment.getUser().environment.getColor()) ){
          var table = main.engine.environment.getTable(), active = table.environment.getActivePiece();
          if(active){
              active.blur();
          }
          
          if(active!=this){
              this.environment.getElement().attribute.addClass("Selected");
              table.environment.setActivePiece(this);
              main.engine.environment.getTable().highlight(
                  this.environment.getMovement(), this
              );
          }
      }
    },
    "move":function(_x,_y){
        var table = main.engine.environment.getTable();
        table.environment.setTime(Number(new Date));
        
        var map = main.engine.environment.getTable().environment.getMap(),
        cell = map[_x][_y],
        oldCell = this.environment.getSquare(),
        capturedPiece = cell.environment.getPiece(),
        promotion = false,
        castling = null,
        movelist = table.element["get"+(this.environment.getColor()&&"Black"||"White")+"MoveList"]();
        
        this.environment.getHistory().push({ "x":_x, "y":_y, "capturedPiece":capturedPiece });
        
        cell.environment.setPiece(this);
        if(oldCell)oldCell.environment.setPiece(null);
        if(this.environment.getValue()==1&&( (this.environment.getColor()==0&&_y==7)|| (this.environment.getColor()==1&&_y==0) )){
            this.environment.setValue(5);
            promotion = true;
        }
        
        var king = table.environment.getKing()[ this.environment.getColor() ]; // kingo disco kingo disco
        if(this.environment.getValue()==4&&_y==this.environment.getColor()*7&&oldCell&&this.environment.getHistory().length==2&&king.environment.getHistory().length==2&&(
          (_x==3&&king.environment.getSquare().environment.getX()==2)||
          (_x==5&&king.environment.getSquare().environment.getX()==6)
        )){
           castling = _x==5&&Piece.KINGSIDE||Piece.QUEENSIDE;
           movelist.child.remove(movelist.element.childNodes[ movelist.element.childNodes.length-1 ]);
        }

        if(table.environment.getIsInitialized()){
         movelist.child.add(
            new pi.element("div").update(cell.getName(capturedPiece,false,castling,promotion))
          );
        }
        
        return this;
    },
    "remove":function(){
        this.environment.getElement().environment.addStyle({ display:"none" });
        this.environment.setSquare(null);
    },
    "undo":function(){
      var latestMove = this.environment.getHistory().getLatest(),
      previousMove = this.environment.getHistory()[ this.environment.getHistory().length-2 ],
      currentMove = this.environment.getHistory()[ this.environment.getHistory().length-1 ];
      
      this.move(
        previousMove.x, previousMove.y
      );
      this.environment.setHistory(
        this.environment.getHistory().slice(0,this.environment.getHistory().length-2)
      );
      
      if(currentMove.removedPiece){
        currentMove.removedPiece.environment.getElement().environment.addStyle({ display:"block" });
        currentMove.removedPiece.move(currentMove.x,currentMove.y);
      }
      
      var
      table = main.engine.environment.getTable(),
      history = table.element["get"+(this.environment.getColor()?"Black":"White")+"MoveList"](),
      childs = history.child.get();
      history.child.remove(
        childs[childs.length-1]
      );
      history.child.remove(
        childs[childs.length-1]
      );
      table.environment.setNext(table.environment.getUser());
    },
    "environment":{
        "_color":0, "_element":null, "_history":null, "_id":0, "_movement":null, "_serverTime":0, "_square":null, "_time":0, "_user":null, "_value":0,
        "setColor":function(_value){
            this._setColor(_value);
            return this._parent_;
        },
        "setSquare":function(_value){
            if(_value)
                this.getElement().addStyle({ "left":_value.getLeft()+"px", "top":_value.getTop()+"px" });
            this._setSquare(_value);
            console.log("=== Square object of "+this.getId()+" was setted to "+(_value));
            return this._parent_;
        },
        "setValue":function(_value){
            this.getElement().attribute.set("title",Piece.Naming[main.engine.environment.getDefaultLanguage()].name[6-_value]);
            this._setValue(_value);
            this._parent_.setClassName();
            return this._parent_;
        }
    }
});

Piece.Move = function(_piece,_cell){
  var table = main.engine.environment.getTable();
  if(
    debug || (
      table.environment.getUser()==table.environment.getNext()
      &&
      main.engine.environment.getTable().environment.getOpponent()
      &&
      ( !_cell.environment.getPiece() || !(_cell.environment.getPiece() instanceof King) )
    )
  ){
    console.log("// User moved "+_piece.environment.getId()+" to ",_cell.environment.getX()+"x"+_cell.environment.getY());
    var response = main.engine.environment.getActiveServer().move(
      _piece.environment.getId(), _cell.environment.getX(), _cell.environment.getY()
    );

    _piece.move(_cell.environment.getX(),_cell.environment.getY());
      
    table.environment.setNext(
      table.environment.getOpponent()
    );
  }
}

Piece.Naming = {
  'belarusian':{ name:['кароль','візыр','ладзьдзя','афіцэр','вершнік','латнік'], mark:[ 'К','Вз','Лд','А','В','Л'] },
  'bg':{ name:['цар','дама','топ','офицер','кон','пешка'], mark:[ 'Ц','Д','Т','О','К','П'] }, 
  'ca':{ name:['rei','dama','torre','alfil','cavall','peó'], mark:[ 'R','D','T','A','C','P'] }, 
  'zh-CN':{ name:['王','后','車','象','馬',''], mark:[ 'K','Q','R','B','N','P'] }, 
  'hr':{ name:['kralj','dama','top','lovac','skakač','pješak'], mark:[ 'K','D','T','L','S','P'] },
  'cs':{ name:['král','dáma','věž','střelec','jezdec','pěšec'], mark:[ 'K','D','V','S','J','P'] }, 
  'da':{ name:['konge','dronning','tårn','løber','springer','bonde'], mark:[ 'K','D','T','L','S','B'] },
  'nl':{ name:['koning','dame','toren','loper','paard','pion'], mark:[ 'K','D','T','L','P','P'] },
  'en':{ name:['king','queen','rook','bishop','knight','pawn'], mark:[ 'K','Q','R','B','N','P'] }, 
  'esperanto':{ name:['reĝo','damo','turo','kuriero','ĉevalo','peono'], mark:[ 'R','D','T','K','Ĉ','P'] }, 
  'estonian':{ name:['kuningas','lipp','vanker','oda','ratsu','ettur'], mark:[ 'K','L','V','O','R','E'] }, 
  'fi':{ name:['kuningas','daami','torni','lähetti','ratsu','sotilas'], mark:[ 'K','D','T','L','R','S'] }, 
  'fr':{ name:['roi','dame','tour','fou','cavalier','pion'], mark:[ 'R','D','T','F','C','P'] }, 
  'de':{ name:['König','Dame','Turm','Läufer','Springer','Bauer'], mark:[ 'K','D','T','L','S','B'] }, 
  'el':{ name:['βασιλιάς','βασίλισσα','πύργος','αξιωματικός','ίππος','πιόνι'], mark:[ 'Ρ','Β','Π','Α','Ι','Σ'] }, 
  'iw':{ name:['מלך','מלכה','צריח','רץ','פרש',''], mark:[ 'מ','מה','צ','ר','פ',''] }, 
  'hi':{ name:['raja','vajeer','hathi','oont','ghoda','pyada'], mark:[ 'R','V','H','O','G','P'] }, 
  'hungarian':{ name:['király','vezér','bástya','futó','huszár','gyalog'], mark:[ 'K','V','B','F','H','P'] },
  'icelandic':{ name:['kóngur','drottning','hrókur','biskup','riddari','peð'], mark:[ 'K','D','H','B','R','P'] },
  'id':{ name:['raja','menteri','benteng','gajah','kuda','pion'], mark:[ 'R','M','B','G','K','P'] }, 
  'irish':{ name:['rí','banríon','caiseal','easpag','ridire','fichillín'], mark:[ 'R','B','C','E','D','F'] }, 
  'it':{ name:['re','donna','torre','alfiere','cavallo','pedone'], mark:[ 'R','D','T','A','C','P'] }, 
  'ja':{ name:['キング','クイーン','ルーク','ビショップ','ナイト','ポーン'], mark:['K','Q','R','B','N','P'] }, 
  'ko':{ name:['킹','퀸','룩','비숍','나이트','폰'], mark:[ 'K','Q','R','B','N','P'] }, 
  'latin':{ name:['rex','regina','turris','episcopus','eques','pedes'], mark:[ 'K','G','T','E','Q','P'] },
  'lv':{ name:['karalis','dāma','tornis','laidnis','zirgs','bandinieks'], mark:[ 'K','D','T','L','Z','B'] },
  'lt':{ name:['karalius','valdovė','bokštas','rikis','žirgas','pėstininkas'], mark:[ 'K','V','B','R','Ž','P'] }, 
  'luxembourgish':{ name:['kinnek','damm','tuerm','leefer','päerd','bauer'], mark:[ 'K','D','T','L','P','B'] },
  'no':{ name:['konge','dronning','tårn','løper','springer','bonde'], mark:[ 'K','D','T','L','S','B'] },
  'persian':{ name:['شاه','وزیر','قلعه','فیل','اسب','سرباز'], mark:[ 'ش','و','ق','ف','ا','س'] },
  'pl':{ name:['król','','wieża','goniec','skoczek','pion'], mark:[ 'K','H','W','G','S','P'] }, 
  'pt':{ name:['rei','dama','torre','bispo','cavalo','peão'], mark:[ 'R','D','T','B','C','P'] }, 
  'ro':{ name:['rege','regină','turn','nebun','cal','pion'], mark:[ 'R','D','T','N','C','P'] }, 
  'ru':{ name:['король','ферзь','ладья','слон','конь','пешка'], mark:[ 'Кр','Ф','Л','С','К','П'] }, 
  'sr':{ name:['краљ','дама','топ','ловац','скакач','пешак'], mark:[ 'К','Д','Т','Л','С','П'] }, 
  'sicilian':{ name:['re','riggina','turru','alferu','scecchu','pidinu'], mark:[ 'R','D','T','A','S','P'] }, 
  'sk':{ name:['kráľ','dáma','veža','strelec','jazdec','pešiak'], mark:[ 'K','D','V','S','J','P'] }, 
  'sl':{ name:['kralj','dama','trdnjava','lovec','skakač','kmet'], mark:[ 'K','D','T','L','S','P'] },
  'es':{ name:['rey','dama','torre','alfil','caballo','peón'], mark:[ 'R','D','T','A','C','P'] }, 
  'sv':{ name:['kung','dam','torn','löpare','springare','bonde'], mark:[ 'K','D','T','L','S','B'] }, 
  'tr':{ name:['şah','vezir','kale','fil','at','piyon'], mark:[ 'Ş','V','K','F','A','P'] }, 
  'uk':{ name:['король','королева','тура','слон','кінь','пішак'], mark:[ 'Kр','D','T','C','K','П'] }, 
  'vi':{ name:['Vua','Hậu','Xe','Tượng','Mã','Tốt'], mark:[ 'V','H','X','T','M','_'] }, 
  'welsh':{ name:['teyrn/brenin','brenhines','castell','esgob','marchog','gwerinwr'], mark:[ 'T','B','C','E','M','G'] }
}

Piece.KINGSIDE = new Object;
Piece.QUEENSIDE = new Object;
